Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
from google.colab import drive
drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
#Do this to see 'workspace_utils' in the import list
%cd /content/drive/MyDrive/aipnd-project-master/aipnd-project-master
root_dir = '/content/drive/MyDrive/aipnd-project-master/aipnd-project-master'
/content/drive/MyDrive/aipnd-project-master/aipnd-project-master
! pip install tensorflow matplotlib
! pip install tensorflow-datasets
! pip install tf-keras
Requirement already satisfied: tensorflow in /usr/local/lib/python3.11/dist-packages (2.18.0) Requirement already satisfied: matplotlib in /usr/local/lib/python3.11/dist-packages (3.10.0) Requirement already satisfied: absl-py>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.4.0) Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.6.3) Requirement already satisfied: flatbuffers>=24.3.25 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (25.2.10) Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.6.0) Requirement already satisfied: google-pasta>=0.1.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.2.0) Requirement already satisfied: libclang>=13.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (18.1.1) Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (3.4.0) Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from tensorflow) (24.2) Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (4.25.6) Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.32.3) Requirement already satisfied: setuptools in /usr/local/lib/python3.11/dist-packages (from tensorflow) (75.1.0) Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.17.0) Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.5.0) Requirement already satisfied: typing-extensions>=3.6.6 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (4.12.2) Requirement already satisfied: wrapt>=1.11.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.17.2) Requirement already satisfied: grpcio<2.0,>=1.24.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.70.0) Requirement already satisfied: tensorboard<2.19,>=2.18 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.18.0) Requirement already satisfied: keras>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (3.8.0) Requirement already satisfied: numpy<2.1.0,>=1.26.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.26.4) Requirement already satisfied: h5py>=3.11.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (3.12.1) Requirement already satisfied: ml-dtypes<0.5.0,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.4.1) Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.37.1) Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.3.1) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (0.12.1) Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (4.56.0) Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.4.8) Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (11.1.0) Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (3.2.1) Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (2.8.2) Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from astunparse>=1.6.0->tensorflow) (0.45.1) Requirement already satisfied: rich in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow) (13.9.4) Requirement already satisfied: namex in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow) (0.0.8) Requirement already satisfied: optree in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow) (0.14.0) Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow) (3.4.1) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow) (3.10) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow) (2.3.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow) (2025.1.31) Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow) (3.7) Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow) (0.7.2) Requirement already satisfied: werkzeug>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow) (3.1.3) Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.11/dist-packages (from werkzeug>=1.0.1->tensorboard<2.19,>=2.18->tensorflow) (3.0.2) Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow) (3.0.0) Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow) (2.18.0) Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich->keras>=3.5.0->tensorflow) (0.1.2) Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.11/dist-packages (4.9.7) Requirement already satisfied: absl-py in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (1.4.0) Requirement already satisfied: click in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (8.1.8) Requirement already satisfied: dm-tree in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (0.1.9) Requirement already satisfied: immutabledict in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (4.2.1) Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (1.26.4) Requirement already satisfied: promise in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (2.3) Requirement already satisfied: protobuf>=3.20 in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (4.25.6) Requirement already satisfied: psutil in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (5.9.5) Requirement already satisfied: pyarrow in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (17.0.0) Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (2.32.3) Requirement already satisfied: simple-parsing in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (0.1.7) Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (1.16.1) Requirement already satisfied: termcolor in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (2.5.0) Requirement already satisfied: toml in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (0.10.2) Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (4.67.1) Requirement already satisfied: wrapt in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (1.17.2) Requirement already satisfied: array-record>=0.5.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow-datasets) (0.6.0) Requirement already satisfied: etils>=1.9.1 in /usr/local/lib/python3.11/dist-packages (from etils[edc,enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (1.12.0) Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from etils[edc,enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (2024.10.0) Requirement already satisfied: importlib_resources in /usr/local/lib/python3.11/dist-packages (from etils[edc,enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (6.5.2) Requirement already satisfied: typing_extensions in /usr/local/lib/python3.11/dist-packages (from etils[edc,enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (4.12.2) Requirement already satisfied: zipp in /usr/local/lib/python3.11/dist-packages (from etils[edc,enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (3.21.0) Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests>=2.19.0->tensorflow-datasets) (3.4.1) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests>=2.19.0->tensorflow-datasets) (3.10) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests>=2.19.0->tensorflow-datasets) (2.3.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests>=2.19.0->tensorflow-datasets) (2025.1.31) Requirement already satisfied: attrs>=18.2.0 in /usr/local/lib/python3.11/dist-packages (from dm-tree->tensorflow-datasets) (25.1.0) Requirement already satisfied: six in /usr/local/lib/python3.11/dist-packages (from promise->tensorflow-datasets) (1.17.0) Requirement already satisfied: docstring-parser<1.0,>=0.15 in /usr/local/lib/python3.11/dist-packages (from simple-parsing->tensorflow-datasets) (0.16) Requirement already satisfied: googleapis-common-protos<2,>=1.56.4 in /usr/local/lib/python3.11/dist-packages (from tensorflow-metadata->tensorflow-datasets) (1.66.0) Requirement already satisfied: tf-keras in /usr/local/lib/python3.11/dist-packages (2.18.0) Requirement already satisfied: tensorflow<2.19,>=2.18 in /usr/local/lib/python3.11/dist-packages (from tf-keras) (2.18.0) Requirement already satisfied: absl-py>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.4.0) Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.6.3) Requirement already satisfied: flatbuffers>=24.3.25 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (25.2.10) Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (0.6.0) Requirement already satisfied: google-pasta>=0.1.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (0.2.0) Requirement already satisfied: libclang>=13.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (18.1.1) Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (3.4.0) Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (24.2) Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (4.25.6) Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (2.32.3) Requirement already satisfied: setuptools in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (75.1.0) Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.17.0) Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (2.5.0) Requirement already satisfied: typing-extensions>=3.6.6 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (4.12.2) Requirement already satisfied: wrapt>=1.11.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.17.2) Requirement already satisfied: grpcio<2.0,>=1.24.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.70.0) Requirement already satisfied: tensorboard<2.19,>=2.18 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (2.18.0) Requirement already satisfied: keras>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (3.8.0) Requirement already satisfied: numpy<2.1.0,>=1.26.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (1.26.4) Requirement already satisfied: h5py>=3.11.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (3.12.1) Requirement already satisfied: ml-dtypes<0.5.0,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (0.4.1) Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow<2.19,>=2.18->tf-keras) (0.37.1) Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from astunparse>=1.6.0->tensorflow<2.19,>=2.18->tf-keras) (0.45.1) Requirement already satisfied: rich in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (13.9.4) Requirement already satisfied: namex in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (0.0.8) Requirement already satisfied: optree in /usr/local/lib/python3.11/dist-packages (from keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (0.14.0) Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow<2.19,>=2.18->tf-keras) (3.4.1) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow<2.19,>=2.18->tf-keras) (3.10) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow<2.19,>=2.18->tf-keras) (2.3.0) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorflow<2.19,>=2.18->tf-keras) (2025.1.31) Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow<2.19,>=2.18->tf-keras) (3.7) Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow<2.19,>=2.18->tf-keras) (0.7.2) Requirement already satisfied: werkzeug>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.19,>=2.18->tensorflow<2.19,>=2.18->tf-keras) (3.1.3) Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.11/dist-packages (from werkzeug>=1.0.1->tensorboard<2.19,>=2.18->tensorflow<2.19,>=2.18->tf-keras) (3.0.2) Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (3.0.0) Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.11/dist-packages (from rich->keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (2.18.0) Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.11/dist-packages (from markdown-it-py>=2.2.0->rich->keras>=3.5.0->tensorflow<2.19,>=2.18->tf-keras) (0.1.2)
# TODO: Make all necessary imports.
import tensorflow_datasets as tfds
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers, models
from tensorflow.keras.models import load_model
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import json
import seaborn as sns
from PIL import Image
import os
batch_size = 32
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
# TODO: Create a training set, a validation set and a test set.
(training_set, validation_set, testing_set), info = tfds.load(
'oxford_flowers102',
split=['train[:80%]', 'train[80%:90%]', 'test'],
with_info=True,
as_supervised=True
)
print(info)
tfds.core.DatasetInfo(
name='oxford_flowers102',
full_name='oxford_flowers102/2.1.1',
description="""
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly
occurring in the United Kingdom. Each class consists of between 40 and 258
images. The images have large scale, pose and light variations. In addition,
there are categories that have large variations within the category and several
very similar categories.
The dataset is divided into a training set, a validation set and a test set. The
training set and validation set each consist of 10 images per class (totalling
1020 images each). The test set consists of the remaining 6149 images (minimum
20 per class).
Note: The dataset by default comes with a test size larger than the train size.
For more info see this
[issue](https://github.com/tensorflow/datasets/issues/3022).
""",
homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
data_dir='/root/tensorflow_datasets/oxford_flowers102/2.1.1',
file_format=tfrecord,
download_size=Unknown size,
dataset_size=331.34 MiB,
features=FeaturesDict({
'file_name': Text(shape=(), dtype=string),
'image': Image(shape=(None, None, 3), dtype=uint8),
'label': ClassLabel(shape=(), dtype=int64, num_classes=102),
}),
supervised_keys=('image', 'label'),
disable_shuffling=False,
splits={
'test': <SplitInfo num_examples=6149, num_shards=2>,
'train': <SplitInfo num_examples=1020, num_shards=1>,
'validation': <SplitInfo num_examples=1020, num_shards=1>,
},
citation="""@InProceedings{Nilsback08,
author = "Nilsback, M-E. and Zisserman, A.",
title = "Automated Flower Classification over a Large Number of Classes",
booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
year = "2008",
month = "Dec"
}""",
)
print(info.description)
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring in the United Kingdom. Each class consists of between 40 and 258 images. The images have large scale, pose and light variations. In addition, there are categories that have large variations within the category and several very similar categories. The dataset is divided into a training set, a validation set and a test set. The training set and validation set each consist of 10 images per class (totalling 1020 images each). The test set consists of the remaining 6149 images (minimum 20 per class). Note: The dataset by default comes with a test size larger than the train size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
print(info.splits)
{'train': <SplitInfo num_examples=1020, num_shards=1>, 'test': <SplitInfo num_examples=6149, num_shards=2>, 'validation': <SplitInfo num_examples=1020, num_shards=1>}
print(info.features)
FeaturesDict({
'file_name': Text(shape=(), dtype=string),
'image': Image(shape=(None, None, 3), dtype=uint8),
'label': ClassLabel(shape=(), dtype=int64, num_classes=102),
})
# TODO: Get the number of examples in each set from the dataset info.
print(f'The number of eamaples in training dataset is : {info.splits["train"].num_examples}')
print(f'The number of eamaples in test dataset is : {info.splits["test"].num_examples}')
print(f'The number of eamaples in validation dataset is : {info.splits["validation"].num_examples}')
print('*'*80)
# TODO: Get the number of classes in the dataset from the dataset info.
print(f'The number of classes is : {info.features["label"].num_classes}')
The number of eamaples in training dataset is : 1020 The number of eamaples in test dataset is : 6149 The number of eamaples in validation dataset is : 1020 ******************************************************************************** The number of classes is : 102
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
image = image.numpy()
label = label.numpy()
plt.imshow(image)
plt.show()
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image, label in training_set.take(1):
image = image.numpy()
label = label.numpy()
plt.title(f'Image Label : {label}')
plt.imshow(image)
plt.show()
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open(root_dir +'/label_map.json', 'r') as f:
class_names = json.load(f)
class_names
{'0': 'pink primrose',
'1': 'hard-leaved pocket orchid',
'2': 'canterbury bells',
'3': 'sweet pea',
'4': 'english marigold',
'5': 'tiger lily',
'6': 'moon orchid',
'7': 'bird of paradise',
'8': 'monkshood',
'9': 'globe thistle',
'10': 'snapdragon',
'11': "colt's foot",
'12': 'king protea',
'13': 'spear thistle',
'14': 'yellow iris',
'15': 'globe-flower',
'16': 'purple coneflower',
'17': 'peruvian lily',
'18': 'balloon flower',
'19': 'giant white arum lily',
'20': 'fire lily',
'21': 'pincushion flower',
'22': 'fritillary',
'23': 'red ginger',
'24': 'grape hyacinth',
'25': 'corn poppy',
'26': 'prince of wales feathers',
'27': 'stemless gentian',
'28': 'artichoke',
'29': 'sweet william',
'30': 'carnation',
'31': 'garden phlox',
'32': 'love in the mist',
'33': 'mexican aster',
'34': 'alpine sea holly',
'35': 'ruby-lipped cattleya',
'36': 'cape flower',
'37': 'great masterwort',
'38': 'siam tulip',
'39': 'lenten rose',
'40': 'barbeton daisy',
'41': 'daffodil',
'42': 'sword lily',
'43': 'poinsettia',
'44': 'bolero deep blue',
'45': 'wallflower',
'46': 'marigold',
'47': 'buttercup',
'48': 'oxeye daisy',
'49': 'common dandelion',
'50': 'petunia',
'51': 'wild pansy',
'52': 'primula',
'53': 'sunflower',
'54': 'pelargonium',
'55': 'bishop of llandaff',
'56': 'gaura',
'57': 'geranium',
'58': 'orange dahlia',
'59': 'pink-yellow dahlia?',
'60': 'cautleya spicata',
'61': 'japanese anemone',
'62': 'black-eyed susan',
'63': 'silverbush',
'64': 'californian poppy',
'65': 'osteospermum',
'66': 'spring crocus',
'67': 'bearded iris',
'68': 'windflower',
'69': 'tree poppy',
'70': 'gazania',
'71': 'azalea',
'72': 'water lily',
'73': 'rose',
'74': 'thorn apple',
'75': 'morning glory',
'76': 'passion flower',
'77': 'lotus',
'78': 'toad lily',
'79': 'anthurium',
'80': 'frangipani',
'81': 'clematis',
'82': 'hibiscus',
'83': 'columbine',
'84': 'desert-rose',
'85': 'tree mallow',
'86': 'magnolia',
'87': 'cyclamen',
'88': 'watercress',
'89': 'canna lily',
'90': 'hippeastrum',
'91': 'bee balm',
'92': 'ball moss',
'93': 'foxglove',
'94': 'bougainvillea',
'95': 'camellia',
'96': 'mallow',
'97': 'mexican petunia',
'98': 'bromelia',
'99': 'blanket flower',
'100': 'trumpet creeper',
'101': 'blackberry lily'}
# TODO: Plot 1 image from the training set. Set the title
for image, label in training_set.take(1):
image = image.numpy()
label = label.numpy()
plt.title(f'Image Class : {class_names[str(label)]}')
plt.imshow(image)
plt.show()
def format_image(image, label):
image = tf.image.resize(image, (224, 224))
image = image / 255.0
return image, label
for images, labels in training_set.take(1):
print(images.shape)
(500, 667, 3)
training_set = training_set.map(format_image)
validation_set = validation_set.map(format_image)
testing_set = testing_set.map(format_image)
training_set = training_set.shuffle(buffer_size=1000).batch(batch_size).prefetch(buffer_size=tf.data.AUTOTUNE)
validation_set = validation_set.batch(batch_size).prefetch(buffer_size=tf.data.AUTOTUNE)
testing_set = testing_set.batch(batch_size).prefetch(buffer_size=tf.data.AUTOTUNE)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
def build_model(input_shape, classes_number):
base_model = tf.keras.applications.MobileNetV2(
input_shape=input_shape,
alpha=1.0,
include_top=False,
weights="imagenet",
)
base_model.trainable = False
model = models.Sequential([
base_model,
layers.GlobalAveragePooling2D(),
layers.Dense(classes_number, activation="softmax")
])
model.compile(
optimizer=tf.keras.optimizers.Adam(),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
return model
input_shape = (224, 224, 3)
classes_number = 102
model = build_model(input_shape, classes_number)
model.summary()
Model: "sequential_1"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩ │ mobilenetv2_1.00_224 (Functional) │ (None, 7, 7, 1280) │ 2,257,984 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ global_average_pooling2d_1 │ (None, 1280) │ 0 │ │ (GlobalAveragePooling2D) │ │ │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dense_1 (Dense) │ (None, 102) │ 130,662 │ └──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
Total params: 2,388,646 (9.11 MB)
Trainable params: 130,662 (510.40 KB)
Non-trainable params: 2,257,984 (8.61 MB)
for images, labels in training_set.take(1):
print(images.shape, labels.shape)
(32, 224, 224, 3) (32,)
for image, label in training_set.take(1):
print("Image Shape:", image.shape)
print("Label Shape:", label.shape)
Image Shape: (32, 224, 224, 3) Label Shape: (32,)
history = model.fit(
training_set,
epochs=10,
validation_data=validation_set
)
Epoch 1/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 25s 360ms/step - accuracy: 0.0351 - loss: 4.7889 - val_accuracy: 0.2059 - val_loss: 3.5498 Epoch 2/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 3s 65ms/step - accuracy: 0.5587 - loss: 2.6032 - val_accuracy: 0.5882 - val_loss: 2.4466 Epoch 3/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 3s 48ms/step - accuracy: 0.8464 - loss: 1.4509 - val_accuracy: 0.6569 - val_loss: 1.9177 Epoch 4/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 2s 46ms/step - accuracy: 0.9552 - loss: 0.8864 - val_accuracy: 0.6863 - val_loss: 1.6265 Epoch 5/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 2s 41ms/step - accuracy: 0.9733 - loss: 0.5636 - val_accuracy: 0.6961 - val_loss: 1.4731 Epoch 6/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 2s 43ms/step - accuracy: 0.9953 - loss: 0.3869 - val_accuracy: 0.7353 - val_loss: 1.3660 Epoch 7/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 3s 63ms/step - accuracy: 1.0000 - loss: 0.2900 - val_accuracy: 0.7353 - val_loss: 1.2963 Epoch 8/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 4s 44ms/step - accuracy: 1.0000 - loss: 0.2270 - val_accuracy: 0.7353 - val_loss: 1.2353 Epoch 9/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 2s 43ms/step - accuracy: 1.0000 - loss: 0.1804 - val_accuracy: 0.7157 - val_loss: 1.2119 Epoch 10/10 26/26 ━━━━━━━━━━━━━━━━━━━━ 2s 42ms/step - accuracy: 1.0000 - loss: 0.1442 - val_accuracy: 0.7549 - val_loss: 1.1700
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
# Extract loss and accuracy from the history object
train_loss = history.history['loss']
val_loss = history.history['val_loss']
train_acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
# Plot Training & Validation Loss
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.plot(train_loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
# Plot Training & Validation Accuracy
plt.subplot(1, 2, 2)
plt.plot(train_acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
# Show the plots
plt.tight_layout()
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
test_loss, test_acc = model.evaluate(testing_set)
print(f"Test Loss: {test_loss:.4f}")
print(f"Test Accuracy: {test_acc:.4f}")
193/193 ━━━━━━━━━━━━━━━━━━━━ 14s 72ms/step - accuracy: 0.7383 - loss: 1.1821 Test Loss: 1.1903 Test Accuracy: 0.7325
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
model.save("flower_classifier_model_v1.h5")
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`.
Load the Keras model you saved above.
# TODO: Load the Keras model
loaded_model = load_model("flower_classifier_model_v1.h5")
loaded_model.summary()
WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.
Model: "sequential_1"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩ │ mobilenetv2_1.00_224 (Functional) │ (None, 7, 7, 1280) │ 2,257,984 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ global_average_pooling2d_1 │ (None, 1280) │ 0 │ │ (GlobalAveragePooling2D) │ │ │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤ │ dense_1 (Dense) │ (None, 102) │ 130,662 │ └──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
Total params: 2,388,648 (9.11 MB)
Trainable params: 130,662 (510.40 KB)
Non-trainable params: 2,257,984 (8.61 MB)
Optimizer params: 2 (12.00 B)
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image):
image = tf.convert_to_tensor(image)
image = tf.image.resize(image, (224, 224))
image = image / 255.0
image = np.expand_dims(image.numpy(), axis=0)
return image
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
def prepare_image(image_path):
image = Image.open(image_path)
test_image = np.asarray(image)
processed_image = process_image(test_image)
processed_test_image = np.squeeze(processed_image)
# Create a subplot to display the original and processed images
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
# Adjust layout and display the images
plt.tight_layout()
plt.show()
return processed_image
image_path = root_dir+'/test_images/hard-leaved_pocket_orchid.jpg'
prepare_image(image_path)
array([[[[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
...,
[0.02390149, 0.01213679, 0.1964505 ],
[0.00843841, 0. , 0.18098743],
[0.01719193, 0.00542722, 0.18974094]],
[[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
...,
[0.02187913, 0.01011443, 0.19442815],
[0.01748074, 0.00571604, 0.19002976],
[0.02290796, 0.01114326, 0.19545698]],
[[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
[0. , 0.00392157, 0.18431373],
...,
[0.01929273, 0.00752803, 0.19184175],
[0.02412468, 0.01235998, 0.1966737 ],
[0.02933304, 0.01756833, 0.20188205]],
...,
[[0. , 0.0035453 , 0.08197667],
[0. , 0.0035453 , 0.08197667],
[0. , 0.0035453 , 0.08197667],
...,
[0.00746687, 0.0035453 , 0.1254902 ],
[0.00107168, 0.00107168, 0.1108756 ],
[0.0002318 , 0.0002318 , 0.11003572]],
[[0. , 0.00392157, 0.08235294],
[0. , 0.00392157, 0.08235294],
[0. , 0.00392157, 0.08235294],
...,
[0.005716 , 0.00179443, 0.12336306],
[0. , 0. , 0.10980392],
[0. , 0. , 0.10980392]],
[[0. , 0.00392157, 0.08235294],
[0. , 0.00392157, 0.08235294],
[0. , 0.00392157, 0.08235294],
...,
[0. , 0. , 0.10980392],
[0. , 0. , 0.10980392],
[0. , 0. , 0.10980392]]]], dtype=float32)
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
def plot_top_k_classes(top_k_classes, top_k_probs):
top_k_class_names = [class_names[str(idx)] for idx in top_k_classes]
plt.figure(figsize=(8, 6))
plt.barh( top_k_class_names, top_k_probs, color='skyblue')
plt.xlabel('Probability')
plt.title('Top K Flower Predictions')
plt.gca().invert_yaxis() # Invert y-axis to show the highest probability at the top
plt.show()
def predict(image_path, model, top_k=5):
processed_image = prepare_image(image_path)
predictions = model.predict(processed_image)
# Get the top K indices and probabilities
top_k_indices = tf.argsort(predictions, axis=-1, direction='DESCENDING')[:, :top_k]
top_k_probs = tf.gather(predictions, top_k_indices, batch_dims=1)
# Convert to numpy arrays
top_k_probs = top_k_probs.numpy().flatten()
top_k_classes = top_k_indices.numpy().flatten().astype(str)
plot_top_k_classes(top_k_classes, top_k_probs)
for _class, prob in zip(top_k_classes, top_k_probs):
print(f'class name: {class_names[str(_class)]} | Probability: {prob}')
predict(image_path, model, 5)
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 52ms/step
class name: cautleya spicata | Probability: 0.7135442495346069 class name: bee balm | Probability: 0.039389681071043015 class name: cape flower | Probability: 0.026876267045736313 class name: red ginger | Probability: 0.01981206052005291 class name: wallflower | Probability: 0.012421920895576477
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
images_folder = root_dir+'/test_images'
images = [f for f in os.listdir(images_folder) if f.endswith(('jpg', 'png'))]
for image in images:
image_path = images_folder+'/'+image
predict(image_path, model, 5)
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 58ms/step
class name: cautleya spicata | Probability: 0.7135442495346069 class name: bee balm | Probability: 0.039389681071043015 class name: cape flower | Probability: 0.026876267045736313 class name: red ginger | Probability: 0.01981206052005291 class name: wallflower | Probability: 0.012421920895576477
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 57ms/step
class name: hard-leaved pocket orchid | Probability: 0.9861286878585815 class name: tiger lily | Probability: 0.002130052074790001 class name: hippeastrum | Probability: 0.0018806760199368 class name: moon orchid | Probability: 0.0011380749056115746 class name: bearded iris | Probability: 0.0009091363754123449
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 51ms/step
class name: osteospermum | Probability: 0.243073970079422 class name: orange dahlia | Probability: 0.1689888834953308 class name: english marigold | Probability: 0.13518795371055603 class name: black-eyed susan | Probability: 0.0825689360499382 class name: blanket flower | Probability: 0.05844883248209953
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 47ms/step
class name: wild pansy | Probability: 0.94139164686203 class name: mexican aster | Probability: 0.012092647142708302 class name: windflower | Probability: 0.008129311725497246 class name: clematis | Probability: 0.0053136833012104034 class name: balloon flower | Probability: 0.0039602005854249